package com.fwx.springcloud.mylb;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : fengwenxiang
 * @date : 2022/6/25 20:15
 * @description：
 */
@Component
@Slf4j
public class LoadBalancerImp implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public ServiceInstance instance(List<ServiceInstance> list) {

        int index = getReqAndIncre() % list.size();
        return list.get(index);
    }

    private int getReqAndIncre() {
        int curr;
        int next;
        do{
            curr = this.atomicInteger.get();
            next = curr > Integer.MAX_VALUE ? 0 : curr+1;
        }while (!this.atomicInteger.compareAndSet(curr,next));
            log.info("****访问次数，第"+next+"次****");
            return next;
    }
}
